package com.digicom.common.core.utils;

import com.digicom.common.constant.Constants;
import com.digicom.common.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全工具类
 */
public class SecurityUtils {
    private static RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置RedisTemplate
     */
    public static void setRedisTemplate(RedisTemplate<String, Object> template) {
        redisTemplate = template;
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        User user = getLoginUser();
        return user != null ? user.getUserId() : null;
    }

    /**
     * 获取用户名
     */
    public static String getUsername() {
        User user = getLoginUser();
        return user != null ? user.getUsername() : "";
    }

    /**
     * 获取登录用户
     */
    public static User getLoginUser() {
        User user = null;
        try {
            // 从SpringSecurity上下文中获取用户认证信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated()) {
                Object principal = authentication.getPrincipal();
                if (principal instanceof String) {
                    String userId = (String) principal;
                    // 从Redis中获取用户信息
                    if (redisTemplate != null) {
                        String userKey = Constants.LOGIN_USER_KEY + ":" + userId;
                        user = (User) redisTemplate.opsForValue().get(userKey);
                    }
                }
            }
        } catch (Exception e) {
            // 发生异常时返回模拟用户
            return createMockUser();
        }

        // 如果未获取到用户，返回模拟用户
        return user != null ? user : createMockUser();
    }

    /**
     * 判断是否为管理员
     */
    public static boolean isAdmin(User user) {
        return user != null && Constants.USER_TYPE_ADMIN.equals(user.getUserType());
    }

    /**
     * 判断当前用户是否为管理员
     */
    public static boolean isAdmin() {
        return isAdmin(getLoginUser());
    }

    /**
     * 创建模拟用户（仅用于开发测试）
     */
    private static User createMockUser() {
        User user = new User();
        user.setUserId(1L);
        user.setUsername("admin");
        user.setNickname("管理员");
        user.setUserType(Constants.USER_TYPE_ADMIN);
        user.setStatus(Constants.USER_STATUS_NORMAL);
        return user;
    }
} 